"use strict";
const passwordHash = require('yi-password-hash');
const ObjectID = require('mongodb').ObjectID;
const userAuth = require('yi-user-auth');

const middleware = (req, res, next) => {
    let authInfo =  req.context||req.context.authInfo ;
    if(!req.context || !req.context.authInfo){
        return res.err.unauthorized();
    }
    authInfo = authInfo.authInfo;

    req.mongo.collection('user')
        .find({openid: authInfo.openid})
        .limit(1)
        .next(function (err, user) {
            if (err) return res.err.mongoError(err);
            if (!user){
                res.reply({code:10000,message:"账号不存在"});
                return;
            }

            let qrCodeType = req.body.qrCodeType;

            if(qrCodeType==='StoreLogin'){
                req.mongo.collection('store').find({$or:[{userId:user._id},{members:user._id}]}).toArray((e1,r1)=>{
                    if(e1 || !r1 || r1.length===0){
                        return res.reply({code:10001,message:"该账号未注册商铺！"});
                    }

                    user.store = r1;
                    user.role = '';
                    userAuth(user,req,(e,r)=>{
                        if(e)
                            res.err.unknownError(e1);
                        else{
                            delete user.pwd;
                            res.reply({code:0,message:"登录成功",data:r});
                        }
                    });
                });

            }else if(qrCodeType==='MallLogin'){
                req.mongo.collection('mall').find({$or:[{userId:user._id},{members:user._id}]}).toArray((e2,r2)=>{
                    if(e2 || !r2 || r2.length===0){
                        return res.reply({code:10002,message:"该账号未注册商场！"});
                    }
                    user.mall=r2;
                    user.role = '';
                    userAuth(user,req,(e,r)=>{
                        if(e)
                            res.err.unknownError(e);
                        else{
                            delete user.pwd;
                            res.reply({code:0,message:"登录成功",data:r});
                        }
                    });
                });
            }else{
                userAuth(user,req,(e,r)=>{
                    if(e)
                        res.err.unknownError(e);
                    else{
                        delete user.pwd;
                        res.reply({code:0,message:"登录成功",data:r});
                    }
                });
            }
        });
}

module.exports = {
    open:false,
    description: '二维码登录',
    middleware: middleware,
    handler(req, res, next) {

    }
};
